package com.ruoyi.course.service.impl;

import java.util.*;

import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.course.mapper.EqAttendanceRecordMapper;
import com.ruoyi.course.domain.EqAttendanceRecord;
import com.ruoyi.course.service.IEqAttendanceRecordService;

/**
 * 公司打卡模块-考勤记录数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-01
 */
@Service
public class EqAttendanceRecordServiceImpl implements IEqAttendanceRecordService 
{
    @Autowired
    private EqAttendanceRecordMapper eqAttendanceRecordMapper;

    /**
     * 查询公司打卡模块-考勤记录数据
     * 
     * @param attendanceId 公司打卡模块-考勤记录数据主键
     * @return 公司打卡模块-考勤记录数据
     */
    @Override
    public EqAttendanceRecord selectEqAttendanceRecordByAttendanceId(String attendanceId)
    {
        return eqAttendanceRecordMapper.selectEqAttendanceRecordByAttendanceId(attendanceId);
    }

    /**
     * 查询公司打卡模块-考勤记录数据列表
     * 
     * @param eqAttendanceRecord 公司打卡模块-考勤记录数据
     * @return 公司打卡模块-考勤记录数据
     */
    @Override
    public List<EqAttendanceRecord> selectEqAttendanceRecordList(EqAttendanceRecord eqAttendanceRecord)
    {
        return eqAttendanceRecordMapper.selectEqAttendanceRecordList(eqAttendanceRecord);
    }

    /**
     * 新增公司打卡模块-考勤记录数据
     * 
     * @param eqAttendanceRecord 公司打卡模块-考勤记录数据
     * @return 结果
     */
    @Override
    public int insertEqAttendanceRecord(EqAttendanceRecord eqAttendanceRecord)
    {
        return eqAttendanceRecordMapper.insertEqAttendanceRecord(eqAttendanceRecord);
    }

    /**
     * 修改公司打卡模块-考勤记录数据
     * 
     * @param eqAttendanceRecord 公司打卡模块-考勤记录数据
     * @return 结果
     */
    @Override
    public int updateEqAttendanceRecord(EqAttendanceRecord eqAttendanceRecord)
    {
        eqAttendanceRecord.setUpdateTime(DateUtils.getTime());
        return eqAttendanceRecordMapper.updateEqAttendanceRecord(eqAttendanceRecord);
    }

    /**
     * 批量删除公司打卡模块-考勤记录数据
     * 
     * @param attendanceIds 需要删除的公司打卡模块-考勤记录数据主键
     * @return 结果
     */
    @Override
    public int deleteEqAttendanceRecordByAttendanceIds(String[] attendanceIds)
    {
        return eqAttendanceRecordMapper.deleteEqAttendanceRecordByAttendanceIds(attendanceIds);
    }

    /**
     * 删除公司打卡模块-考勤记录数据信息
     * 
     * @param attendanceId 公司打卡模块-考勤记录数据主键
     * @return 结果
     */
    @Override
    public int deleteEqAttendanceRecordByAttendanceId(String attendanceId)
    {
        return eqAttendanceRecordMapper.deleteEqAttendanceRecordByAttendanceId(attendanceId);
    }

    /**
     * 统计指定月份的考勤记录
     *
     * @param date
     * @return
     */
    @Override
    public Map<String, Map<String, Integer>> statistics(String date) {
        // 解析日期参数
        String yearMonth = date.substring(0, 7);

        String[] split = yearMonth.split("-");
        int year = Integer.parseInt(split[0]);
        int month = Integer.parseInt(split[1]);

        List<EqAttendanceRecord> records = eqAttendanceRecordMapper.selectEqAttendanceRecordListByYearAndMonth(year, month);

        Set<String> userIds = new HashSet<>();

        Set<String> dates = new HashSet<>();
        // 统计每个人的数据
        Map<String, Map<String, Object>> result = new HashMap<>();

        for (EqAttendanceRecord r : records) {
            String employeeId = r.getEmployeeId();
            if (!result.containsKey(employeeId)) {
                result.put(employeeId, new HashMap<>());
                result.get(employeeId).put("totalDays", 0);
                result.get(employeeId).put("presentNum", 0);  // 统计正常打卡次数
                result.get(employeeId).put("absentNum", 0);  // 统计异常打卡次数
                result.get(employeeId).put("abnormalNum", 0);  // 统计缺卡打卡次数
                result.get(employeeId).put("presentDays", 0);  // 统计正常打卡天数
                result.get(employeeId).put("absentDays", 0);  // 统计异常打卡天数
                result.get(employeeId).put("abnormalDays", 0);  // 统计缺卡打卡天数
            }

            // 处理打卡记录
            processAttendanceRecord1(result, employeeId, r,userIds,dates);
        }

        for (String userId : userIds) {
            Map<String, Object> stringObjectMap = result.get(userId);
            for (String s : dates) {
                if (stringObjectMap.containsKey(s)) {
                    Object o = stringObjectMap.get(s);
                    List<EqAttendanceRecord> recordList = (List<EqAttendanceRecord>) o;
                    int count = 0;
                    for (EqAttendanceRecord eqAttendanceRecord : recordList) {
                        if (eqAttendanceRecord.getAttendanceStatus().equals("异常")) {
                            stringObjectMap.put("absentDays", (int) stringObjectMap.get("absentDays") + 1);
                            count ++ ;
                            break;
                        }
                        if (eqAttendanceRecord.getAttendanceStatus().equals("缺卡")) {
                            stringObjectMap.put("abnormalDays", (int) stringObjectMap.get("abnormalDays") + 1);
                            count ++ ;
                            break;
                        }
                    }
                    if (count == 0){
                        stringObjectMap.put("presentDays", (int) stringObjectMap.get("presentDays") + 1);
                    }
                }
            }
        }
        // 封装并返回数据
        return calculateAbsentDays1(result);
    }

    /**
     * 处理单条打卡记录
     */
    private void processAttendanceRecord1(Map<String, Map<String, Object>> result,
                                         String employeeId, EqAttendanceRecord record, Set<String> userIds, Set<String> dates) {
        Map<String, Object> stats = result.get(employeeId);

        // 获取日期
        String date = record.getAddTime().substring(0, 10);

        // 检查是否已处理该日期
        if (!stats.containsKey(date)) {
            // 增加总天数（只增加一次）
            Object o = stats.get("totalDays");

            int q = (int) o ;
            stats.put("totalDays", q + 1);
        }

        // 标记为已处理
//        stats.put(date, record);

        // 替换为：
        if (stats.containsKey(date)) {
            Object existingValue = stats.get(date);
            if (existingValue instanceof List) {
                // 如果已经是列表，添加新记录
                ((List<EqAttendanceRecord>) existingValue).add(record);
            } else {
                // 如果是单个记录，转为列表存储
                List<EqAttendanceRecord> recordList = new ArrayList<>();
                if (existingValue instanceof EqAttendanceRecord) {
                    recordList.add((EqAttendanceRecord) existingValue);
                }
                recordList.add(record);
                stats.put(date, recordList);
            }
        } else {
            // 第一次添加该日期
            List<EqAttendanceRecord> recordList = new ArrayList<>();
            recordList.add(record);
            stats.put(date, recordList);
        }

        userIds.add(employeeId);

        dates.add(date);

        // 根据考勤状态更新统计
        String status = record.getAttendanceStatus();
        if ("正常".equals(status)) {
            stats.put("presentNum", (int)stats.get("presentNum") + 1);
        } else if ("异常".equals(status)) {
            stats.put("abnormalNum",  (int)stats.get("abnormalNum") + 1);
        } else if ("缺卡".equals(status)) {
            stats.put("absentNum",  (int)stats.get("absentNum") + 1);
        }

    }

    /**
     * 统计并封装返回结果
     */
    private Map<String,  Map<String, Integer>> calculateAbsentDays1(Map<String, Map<String, Object>> result) {

        Map<String,  Map<String, Integer>> mapList = new HashMap<>();
        for (Map.Entry<String, Map<String, Object>> entry : result.entrySet()) {

            Map<String, Integer> map = new HashMap<>();


            Map<String, Object> stats = entry.getValue();
            int totalDays =  (int)stats.get("totalDays");
            int presentNum =  (int)stats.get("presentNum");
            int abnormalNum =  (int)stats.get("abnormalNum");
            int absentNum =  (int)stats.get("absentNum");
            int presentDays =  (int)stats.get("presentDays");
            int abnormalDays =  (int)stats.get("abnormalDays");
            int absentDays =  (int)stats.get("absentDays");

//            // 缺卡天数 = 总天数 - 正常天数 - 异常天数
//            int absentDays = totalDays - presentDays - abnormalDays;
//            stats.put("absentDays", absentDays);

            String key = entry.getKey();
            map.put("absentNum", absentNum);
            map.put("totalDays", totalDays);
            map.put("presentNum", presentNum);
            map.put("abnormalNum", abnormalNum);
            map.put("presentDays", presentDays);
            map.put("abnormalDays", abnormalDays);
            map.put("absentDays", absentDays);
            mapList.put(key, map);
        }
        return mapList;
    }













    /**
     * 处理单条打卡记录
     */
    private void processAttendanceRecord(Map<String, Map<String, Integer>> result,
                                         String employeeId, EqAttendanceRecord record) {
        Map<String, Integer> stats = result.get(employeeId);

        // 获取日期
        String date = record.getAddTime().substring(0, 10);

        // 检查是否已处理该日期
        if (!stats.containsKey(date)) {
            // 增加总天数（只增加一次）
            stats.put("totalDays", stats.get("totalDays") + 1);
        }

        // 标记为已处理
        stats.put(date, 1);

        // 根据考勤状态更新统计
        String status = record.getAttendanceStatus();
        if ("正常".equals(status)) {
            stats.put("presentNum", stats.get("presentNum") + 1);
        } else if ("异常".equals(status)) {
            stats.put("abnormalNum", stats.get("abnormalNum") + 1);
        } else if ("缺卡".equals(status)) {
            stats.put("absentNum", stats.get("absentNum") + 1);
        }

    }

    /**
     * 统计并封装返回结果
     */
    private Map<String,  Map<String, Integer>> calculateAbsentDays(Map<String, Map<String, Integer>> result) {

        Map<String,  Map<String, Integer>> mapList = new HashMap<>();
        for (Map.Entry<String, Map<String, Integer>> entry : result.entrySet()) {

            Map<String, Integer> map = new HashMap<>();



            Map<String, Integer> stats = entry.getValue();
            int totalDays = stats.get("totalDays");
            int presentNum = stats.get("presentNum");
            int abnormalNum = stats.get("abnormalNum");
            int absentNum = stats.get("absentNum");

//            // 缺卡天数 = 总天数 - 正常天数 - 异常天数
//            int absentDays = totalDays - presentDays - abnormalDays;
//            stats.put("absentDays", absentDays);

            String key = entry.getKey();
            map.put("absentNum", absentNum);
            map.put("totalDays", totalDays);
            map.put("presentNum", presentNum);
            map.put("abnormalNum", abnormalNum);
            mapList.put(key, map);
        }
        return mapList;
    }
}
